package cn.claim.storage.tools;
/**
 * Created by claim on 17-7-7.
 */

import java.io.*;
import java.util.Properties;

/**
 * Save or load program configurations.
 */
public final class Config {
    private final static Properties prop;
    private static File propFile;

    static {
        prop = new Properties();
        try {
            propFile = new File("./config.properties");
            if (!propFile.exists()) {
                //noinspection ResultOfMethodCallIgnored
                propFile.createNewFile();
            }
            Reader reader = new FileReader(propFile);
            prop.load(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Config() {
    }

    /**
     * Get a property in the property list. Return null if no value found.
     */
    public static String getProp(String propKey) {
        return prop.getProperty(propKey);
    }

    public static String getProp(String propKey, String defaultValue) {
        return prop.getProperty(propKey) == null ? defaultValue : prop.getProperty(propKey);
    }

    /**
     * Set a property value, but not save this to a file.
     * You should always invoke method {@code save()} after you set a property.
     */
    public static void setProp(String propKey, String propValue) {
        prop.setProperty(propKey, propValue);
        save();
    }

    /**
     * Save your changes to {@code ./config.properties}.
     */
    public static void save() {
        try {
            Writer writer = new FileWriter(propFile);
            prop.store(writer, null);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    /**
//     * Just for tests.*/
//    public static void main(String[] args) {
//        System.out.println(getProp("account"));
//        setProp("account","123456");
//        System.out.println(getProp("account"));
//        save();
//    }
}
